<template>
  <div class="ai-assistant">
    <!-- 悬浮AI助手图标 -->
    <div class="ai-floating-icon" @click="toggleDialog" :class="{ 'active': isDialogVisible }">


      <div class="ai-icon">
  <img src="@/assets/桃乐丝doro表情包动图39爱给网aigeicom.gif" alt="Animated Cat Girl Dancing" class="cat-girl-image"
          style="width: 100px;height: 100px;">
    
      </div>
    </div>

    <!-- AI对话框 -->
    <div v-if="isDialogVisible" class="ai-dialog" :class="{ 'show': isDialogVisible }">
      <div class="dialog-header">
        <div class="dialog-title">
          <div class="title-icon">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="12" cy="12" r="10" fill="#409eff" />
              <path d="M8 10h8M8 14h6" stroke="white" stroke-width="2" stroke-linecap="round" />
              <circle cx="8" cy="8" r="1" fill="white" />
              <circle cx="16" cy="8" r="1" fill="white" />
            </svg>
          </div>
          <span>MES智能客服</span>
        </div>
        <button class="close-btn" @click="closeDialog">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
          </svg>
        </button>
      </div>

      <div class="dialog-content">
        <div class="welcome-section">
          <div class="welcome-text">
            <h3>欢迎使用MES智能客服</h3>
            <p>我是您的专属MES系统AI助手，可以帮您解答关于物料管理、生产管理、质量管理、工艺管理等各个模块的问题</p>
          </div>

          <div class="quick-actions">
            <button v-for="action in quickActions" :key="action" @click="handleQuickAction(action)"
              class="quick-action-btn">
              {{ action }}
            </button>
          </div>
        </div>

        <div class="chat-section">
          <div class="chat-messages" ref="chatMessages">
            <div v-for="(message, index) in messages" :key="index" class="message"
              :class="{ 'user': !message.isAI, 'ai': message.isAI }">
              <div class="message-content">
                <div class="message-text">{{ message.message }}</div>
                <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              </div>
            </div>

            <div v-if="isLoading" class="message ai">
              <div class="message-content">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                  <span>AI正在思考中...</span>
                </div>
              </div>
            </div>
          </div>

          <div class="chat-input">
            <div class="input-container">
              <input v-model="inputMessage" @keydown.enter="sendMessage" placeholder="请输入您的问题..." :disabled="isLoading"
                class="message-input" />
              <button @click="sendMessage" :disabled="!inputMessage.trim() || isLoading" class="send-btn">
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="currentColor" stroke-width="2"
                    stroke-linecap="round" stroke-linejoin="round" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div v-if="isDialogVisible" class="dialog-overlay" @click="closeDialog"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import ChatService, { type ChatResponse, type ChatSession } from '../api/chat'

// 响应式数据
const isDialogVisible = ref(false)
const isLoading = ref(false)
const inputMessage = ref('')
const messages = ref<ChatResponse[]>([])
const currentSession = ref<ChatSession | null>(null)

// 快速操作按钮
const quickActions = ref([
  '你好，我想了解一下MES系统',
  '物料管理功能',
  '生产管理模块',
  '质量管理流程',
  '工艺管理说明',
  '权限管理设置',
  '仓库管理功能',
  '系统使用帮助'
])

// 引用
const chatMessages = ref<HTMLElement>()


// 方法
const toggleDialog = () => {
  isDialogVisible.value = !isDialogVisible.value
  if (isDialogVisible.value && !currentSession.value) {
    createNewSession()
  }
}

const closeDialog = () => {
  isDialogVisible.value = false
}

const handleQuickAction = (action: string) => {
  inputMessage.value = action
  sendMessage()
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const userMessage = inputMessage.value.trim()
  inputMessage.value = ''

  // 添加用户消息
  const userMsg: ChatResponse = {
    message: userMessage,
    sessionId: currentSession.value?.sessionId || '',
    timestamp: new Date().toISOString(),
    isAI: false
  }
  messages.value.push(userMsg)

  // 滚动到对话底部
  await nextTick()
  scrollToBottom()

  // 发送到AI
  await sendToAI(userMessage)
}

const sendToAI = async (message: string) => {
  if (!currentSession.value) {
    await createNewSession()
  }

  isLoading.value = true

  try {
    const response = await ChatService.sendMessage({
      message,
      sessionId: currentSession.value!.sessionId
    })

    // 添加AI回复
    messages.value.push(response)

    // 滚动到对话底部
    await nextTick()
    scrollToBottom()

  } catch (error: any) {
    console.error('发送消息失败:', error)

    let errorMessage = '抱歉，服务暂时不可用，请稍后再试。'
    if (error.response) {
      errorMessage = `服务器错误 (${error.response.status}): ${error.response.data?.message || error.message}`
    } else if (error.request) {
      errorMessage = '无法连接到服务器，请检查网络连接或确认后端服务是否启动'
    } else {
      errorMessage = `请求错误: ${error.message}`
    }

    const errorMsg: ChatResponse = {
      message: errorMessage,
      sessionId: currentSession.value?.sessionId || '',
      timestamp: new Date().toISOString(),
      isAI: true
    }
    messages.value.push(errorMsg)

    ElMessage.error(`发送消息失败: ${errorMessage}`)
  } finally {
    isLoading.value = false
  }
}

const createNewSession = async () => {
  try {
    currentSession.value = await ChatService.createSession()
  } catch (error) {
    console.error('创建会话失败:', error)
    ElMessage.error('创建会话失败')
  }
}

const scrollToBottom = () => {
  if (chatMessages.value) {
    chatMessages.value.scrollTop = chatMessages.value.scrollHeight
  }
}

const formatTime = (timestamp: string) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}


</script>

<style scoped>
.ai-assistant {
  position: relative;
}

/* 悬浮AI图标 */
.ai-floating-icon {
  position: fixed;
  bottom: 2px;
  right: 70px;
  width: 100px;
  height: 140px;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  z-index: 1000;
  animation: float 3s ease-in-out infinite;
}

.ai-floating-icon:hover {
  transform: scale(1.2) translateY(-5px) rotate(5deg);
  animation-play-state: paused;
}

.ai-floating-icon.active {
  transform: scale(1.15) rotate(-5deg);
  animation: activeGlow 2s ease-in-out infinite alternate;
}

@keyframes float {

  0%,
  100% {
    transform: translateY(0px);
  }

  50% {
    transform: translateY(-10px);
  }
}

@keyframes activeGlow {
  0% {
    filter: drop-shadow(0 0 15px rgba(33, 150, 243, 0.8));
  }

  100% {
    filter: drop-shadow(0 0 25px rgba(33, 150, 243, 1));
  }
}

.ai-icon {
  width: 130px;
  height: 180px;
  color: white;
  filter: drop-shadow(0 0 20px rgba(33, 150, 243, 0.6)) drop-shadow(0 0 40px rgba(100, 181, 246, 0.4));
  animation: iconGlow 2s ease-in-out infinite alternate;
}

.qiqi-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transform: perspective(1000px) rotateY(5deg);
  transition: transform 0.3s ease;
  filter: drop-shadow(0 10px 20px rgba(139, 92, 246, 0.4)) drop-shadow(5px 5px 10px rgba(0, 0, 0, 0.2)) drop-shadow(0 0 20px rgba(139, 92, 246, 0.6)) drop-shadow(0 0 40px rgba(199, 125, 255, 0.4));
  animation: stereoFloat 4s ease-in-out infinite, iconGlow 2s ease-in-out infinite alternate, float 3s ease-in-out infinite;
}

.ai-icon:hover .qiqi-image {
  transform: perspective(1000px) rotateY(-5deg) scale(1.1);
  filter: drop-shadow(0 15px 30px rgba(139, 92, 246, 0.6)) drop-shadow(10px 10px 20px rgba(0, 0, 0, 0.3)) drop-shadow(0 0 20px rgba(139, 92, 246, 0.6)) drop-shadow(0 0 40px rgba(199, 125, 255, 0.4));
}

@keyframes stereoFloat {
  0% {
    transform: perspective(1000px) rotateY(5deg) translateY(0);
  }

  50% {
    transform: perspective(1000px) rotateY(-5deg) translateY(-5px);
  }

  100% {
    transform: perspective(1000px) rotateY(5deg) translateY(0);
  }
}

@media (max-width: 768px) {
  .ai-floating-icon {
    bottom: 20px;
    right: 50px;
    width: 100px;
    height: 140px;
  }

  .ai-icon {
    width: 100px;
    height: 140px;
  }
}

/* SVG内部动画 */
.ai-icon .energy-ring {
  animation: rotate 4s linear infinite;
}

.ai-icon .particle-1 {
  animation: particleFloat 3s ease-in-out infinite;
}

.ai-icon .particle-2 {
  animation: particleFloat 3s ease-in-out infinite 0.5s;
}

.ai-icon .particle-3 {
  animation: particleFloat 3s ease-in-out infinite 1s;
}

.ai-icon .particle-4 {
  animation: particleFloat 3s ease-in-out infinite 1.5s;
}

.ai-icon .energy-core {
  animation: energyPulse 1.5s ease-in-out infinite;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@keyframes particleFloat {

  0%,
  100% {
    transform: translateY(0px) scale(1);
    opacity: 0.8;
  }

  50% {
    transform: translateY(-3px) scale(1.2);
    opacity: 1;
  }
}

@keyframes energyPulse {

  0%,
  100% {
    transform: scale(1);
    opacity: 0.3;
  }

  50% {
    transform: scale(1.5);
    opacity: 0.6;
  }
}

/* AI对话框 */
.ai-dialog {
  position: fixed;
  bottom: 320px;
  right: 30px;
  width: 500px;
  height: 600px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  z-index: 1001;
  display: flex;
  flex-direction: column;
  opacity: 0;
  transform: translateY(20px) scale(0.95);
  transition: all 0.3s ease;
}

.ai-dialog.show {
  opacity: 1;
  transform: translateY(0) scale(1);
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;
  border-radius: 16px 16px 0 0;
}

.dialog-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.title-icon {
  width: 24px;
  height: 24px;
}

.close-btn {
  width: 24px;
  height: 24px;
  border: none;
  background: none;
  cursor: pointer;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: #f0f0f0;
  color: #333;
}

.dialog-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.welcome-section {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.welcome-text {
  text-align: center;
  margin-bottom: 20px;
}

.welcome-text h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.welcome-text p {
  margin: 0;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.quick-actions {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  max-height: 250px;
  overflow-y: auto;
}

.quick-action-btn {
  padding: 8px 12px;
  border: 1px solid #e4e7ed;
  background: white;
  border-radius: 8px;
  font-size: 12px;
  color: #333;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: left;
}

.quick-action-btn:hover {
  background: #f0f9ff;
  border-color: #409eff;
  color: #409eff;
}

.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px 20px;
  max-height: 400px;
}

.message {
  margin-bottom: 12px;
}

.message.user {
  display: flex;
  justify-content: flex-end;
}

.message.ai {
  display: flex;
  justify-content: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 8px 12px;
  border-radius: 12px;
  word-wrap: break-word;
}

.message.user .message-content {
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
}

.message.ai .message-content {
  background: #f0f9ff;
  border: 1px solid #e0f2fe;
  color: #333;
}

.message-text {
  font-size: 13px;
  line-height: 1.4;
}

.message-time {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 4px;
  text-align: right;
}

.message.ai .message-time {
  color: #999;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #666;
}

.typing-indicator span:not(:last-child) {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #409eff;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {

  0%,
  60%,
  100% {
    transform: translateY(0);
    opacity: 0.5;
  }

  30% {
    transform: translateY(-6px);
    opacity: 1;
  }
}

.chat-input {
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
}

.input-container {
  display: flex;
  gap: 8px;
  align-items: center;
}

.message-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e4e7ed;
  border-radius: 20px;
  font-size: 13px;
  outline: none;
  transition: all 0.2s ease;
}

.message-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.send-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: #409eff;
  color: white;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.send-btn:hover:not(:disabled) {
  background: #337ecc;
}

.send-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

.send-btn svg {
  width: 16px;
  height: 16px;
}

/* 遮罩层 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 4px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-dialog {
    width: calc(100vw - 20px);
    height: calc(100vh - 120px);
    bottom: 20px;
    right: 10px;
    left: 10px;
  }

  .ai-floating-icon {
    bottom: 20px;
    right: 20px;
    width: 150px;
    height: 210px;
    background: transparent;
  }

  .ai-icon {
    width: 130px;
    height: 180px;
  }

  .quick-actions {
    grid-template-columns: 1fr;
  }

  .message-content {
    max-width: 90%;
  }
}
</style>
